<template>
  <div class="blog-category-container" v-loading="loading">
    <h2>文章分类</h2>
    <RightList :list="list" @select="handleSelect" />
  </div>
</template>

<script setup lang="ts">
import { useFetchData } from '@/hooks/useFetchData'
import RightList from './RightList.vue'
import { getBlogCategory } from '@/api/blog'
import { computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const route: any = useRoute()
const router: any = useRouter()

const fetchData = () => {
  return getBlogCategory().then((res) => res.data)
}

const { data, loading } = useFetchData<any[]>({
  defaultValue: [],
  fetchData
})

// const routeInfo = computed(() => {
//   const categoryId = +route.params.categoryId || -1
//   const page = +route.query.page || 1
//   const limit = +route.query.limit || 10
//   return {
//     categoryId,
//     page,
//     limit
//   }
// })

const categoryId = computed(() => +route.params.categoryId || -1)
const limit = computed(() => +route.query.limit || 10)

const list = computed(() => {
  const totalArticleCount = data.value.reduce((pre, cur) => pre + cur.articleCount, 0)
  const result = [{ name: '全部', id: -1, articleCount: totalArticleCount }, ...data.value]
  return result.map((it) => ({
    ...it,
    isSelect: it.id === categoryId.value,
    aside: `${it.articleCount}篇`
  }))
})

const handleSelect = (item: any) => {
  const query = {
    page: 1,
    limit: limit.value
  }
  if (item.id === -1) {
    // 当前没有分类
    // /article?page=${newPage}&limit=${this.routeInfo.limit}
    router.push({
      name: 'Blog',
      query
    })
  } else {
    // /article/cate/${this.routeInfo.categoryId}?page=${newPage}&limit=${this.routeInfo.limit}
    router.push({
      name: 'CategoryBlog',
      query,
      params: {
        categoryId: item.id
      }
    })
  }
}
</script>

<style lang="less" scoped>
.blog-category-container {
  width: 300px;
  box-sizing: border-box;
  padding: 20px;
  position: relative;
  height: 100%;
  overflow-y: auto;
  h2 {
    font-weight: bold;
    letter-spacing: 2px;
    font-size: 1em;
    margin: 0;
  }
}
</style>